//
//  PhoneLoginViewController.m
//  Growth
//
//  Created by 洪波 陈 on 6/9/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "PhoneLoginViewController.h"
#import "WebRequest.h"

#import "GrowthAppDelegate.h"
#import "CJSONSerializer.h"

static WebConnection *login_connection;
static WebConnectionArray *timeline_connection;

@interface PhoneLoginViewController ()

@end

@implementation PhoneLoginViewController

@synthesize phoneNumStr;
@synthesize loginkeytextField;


- (void)dealloc
{
    [phoneNumStr release];
    [loginkeytextField release];
    
    if (login_connection != nil) {
        login_connection.connectionDelegate = nil;
        [login_connection release];
        login_connection = nil;
    }
    
    if (timeline_connection != nil) {
        timeline_connection.connectionDelegate = nil;
        [timeline_connection release];
        timeline_connection = nil;
    }
    
    [super dealloc];
}

- (id)initWithPhone:(NSString *)phoneStr
{
    self = [super init];
    if (self) {
        self.phoneNumStr = phoneStr;
    }
    
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"填写密码";
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - Action

- (IBAction)phoneChange:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)loginAction:(id)sender
{
    CLog(@"Login!");

    [loginkeytextField resignFirstResponder];
    
    CLog(@"loginkeytextField.text  %@", loginkeytextField.text);
    if ([loginkeytextField.text isEqualToString:@""] || loginkeytextField.text == nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"密码不能为空" 
                                                       delegate:self 
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        return;
        
    }

    
    [LoadingView showDefaultLoadingView];
    
    
    NSString *loginType = @"meetstudio" ;
    NSString *osType = @"ios";

    NSArray *keys = [NSArray arrayWithObjects:@"loginType",@"appId",@"password",@"account",@"osType", nil];
    
    
    NSArray *objects = [NSArray arrayWithObjects:loginType,[NSNumber numberWithInt:APP_ID], loginkeytextField.text, phoneNumStr,osType, nil];
    
    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
    NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    CLog(@"theBodyString  %@", theBodyString);
    
    //   	
    NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
    //	
    NSMutableURLRequest * request = [WebRequest LoginRequestWith:_jsonData];
    CLog(@"request %@", request);
    if (login_connection != nil) {
        login_connection.connectionDelegate = nil;
    }
    login_connection = [[WebConnection alloc] initWith:request delegate:self dataBaseListName:nil];
}





#pragma mark action 获取到用户信息操作

- (void)loginSuccess{
    
    
    CLog(@"Login success!");
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] != nil) {
        
        [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:REGIST_LOGIN_KEY];
        int uid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue];
        
        
        
        NSString *uidStr = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] stringValue];
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: uidStr, @"uid", @"meetstudio", @"type", @"phone", @"accountType", nil];
        [MobClick event:MobClick_Login attributes:dict];
        
        
        [self loadTimelineMember:uid];
        
    }   
    else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"帐号密码错误！" 
                                                       delegate:self 
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        
    }
    
    
}

- (void)loginErrorWith:(NSString *)info
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"失败!" message:@"连接错误，重新连接！" 
                                                   delegate:self 
                                          cancelButtonTitle:@"取消" otherButtonTitles:nil];
    
    [alert show];
    [alert release];
    
}

- (void)loginError{
    
	[self loginErrorWith:@"密码错误或网络连接失败！"];
}



#pragma mark load data
//下载可管理的时间轴

-(void)loadTimelineMember:(int)uid{
    
    [LoadingView showDefaultLoadingView];
    
    NSMutableURLRequest * request = [WebRequest userTiemlineMemberRequestWith:[NSString stringWithFormat:@"%d",uid]];
	
	CLog(@"request %@", request);
    if (timeline_connection != nil) {
        timeline_connection.connectionDelegate = nil;
    }
	timeline_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:@"TimelineId"];
    
}

#pragma mark - connection delegate

- (void)connectionArraySuccess:(NSDictionary *)dict connectionURL:(NSString *)url{
    
    
    [LoadingView hideWithAnimated:YES];
    
    
    //可管理时间轴
    
    int userId;
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userId"]) {
        userId =[[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue]; 
    }
    
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/mobile/timeline/menu?uid=%d",BASEURL, userId]]) 
    {
        
        
        if ([[dict objectForKey:@"object"] count] >0) {  //保存tid
            
            NSDictionary *timelineDict = [[dict objectForKey:@"object"] objectAtIndex:0];
            
            [[NSUserDefaults standardUserDefaults] setValue:[timelineDict objectForKey:@"id"] forKey:@"timelineId"];
            
            
        }
        
        //登陆成功
        [self userLoginSuccess];
        
        
        
    }
    
    
    
}

- (void)connectionArrayError:(NSError *)error{
    
    
    [LoadingView hideWithAnimated:YES];
    
    self.view.userInteractionEnabled=YES;
    [self loginError];
    
}



- (void)connectionSuccess:(NSDictionary *)dict
{
    [LoadingView hideWithAnimated:YES];

    if(dict){
        
        //帐号验证
        NSInteger errorCode = [[dict objectForKey:@"errorCode"] intValue];
        
        //save usre info
        if((errorCode == 0 || errorCode == 6) && [[dict allKeys] containsObject:@"userId"]){
            [[NSUserDefaults standardUserDefaults] setValue:[dict objectForKey:@"userId"] forKey:@"userId"];
            [[NSUserDefaults standardUserDefaults]setValue:[dict objectForKey:@"userNickname"] forKey:@"userName"];
            [[NSUserDefaults standardUserDefaults]setValue:[dict objectForKey:@"userAttachmentId"] forKey:@"userAttachmentId"];
            
            [[NSUserDefaults standardUserDefaults] setValue:[dict objectForKey:@"Ucenter-Code"] forKey:@"Ucenter-Code"];
            [[NSUserDefaults standardUserDefaults] setValue:[dict objectForKey:@"Ucenter-VerifyCode"] forKey:@"Ucenter-VerifyCode"];
            
            
            [self  loginSuccess]; 
        }
        else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"失败!" message:@"帐号密码错误！" 
                                                           delegate:self 
                                                  cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            [alert release];
            
            return;
        }
        
    }
    
    else{
        [self loginError];
    }
}

- (void)connectionError:(NSError *)error
{
    CLog(@"error info");
    [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"登陆错误！" ];    self.view.userInteractionEnabled=YES;
}
@end
